package com.huika.dealontop.control.shops.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ZoomButtonsController;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAda;
import com.huika.dealontop.control.base.BaseFra;
import com.huika.dealontop.control.shops.activity.ProductDetailsActivity1;
import com.huika.dealontop.control.shops.holder.OtherProductItemHolder;
import com.huika.dealontop.support.domain.OtherProductItemBean;
import com.huika.dealontop.support.domain.ProductDetailsBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.webview.CustomWebView;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Author: Victor Wu <br/>
 * Email: victor-wu*foxmail.com <br/>
 * Time: 2015/11/23 12:01 <br/>
 * Description: 商家其他商品 列表
 */
public class OtherProductListFragment extends BaseFra implements Response.Listener<RequestResult<List<OtherProductItemBean>>>, AdapterView.OnItemClickListener {

    private ProductDetailsBean.ProductBean productDetailsBean;

    private boolean isFirstLoadData;

    private JSONWrapAjaxParams ajaxParams;

    public PullToRefreshListView getPullToRefreshListView() {
        return mLvContent;
    }

    private PullToRefreshListView mLvContent;
    private CustomWebView mWebView;
    private View graphicDetails;
    private View otherCouponTitle;
    private ProductListAdapter mAdapter;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        return View.inflate(UIUtils.getContext(), R.layout.fragment_other_product_list, null);
    }

    @Override
    protected void initWidget(View parentView) {
        mLvContent = (PullToRefreshListView) parentView.findViewById(R.id.lv_other_product);
        mLvContent.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (productDetailsBean != null) {
                    loadMoreData();
                }
            }
        });
        mLvContent.setMode(PullToRefreshBase.Mode.DISABLED);
        createWebView();
        mLvContent.getRefreshableView().addHeaderView(graphicDetails);
        mAdapter = new ProductListAdapter(this.getActivity());
        mLvContent.setAdapter(mAdapter);
        mLvContent.setOnItemClickListener(this);
    }


    public void firstLoadData() {
        if (!isFirstLoadData && productDetailsBean != null) {
            startLoadData();
        }
    }

    private void startLoadData() {
        JSONWrapAjaxParams ajaxParams = getParams();
        ajaxParams.putCommonTypeParam("Page", 1);
        FormResultRequest<List<OtherProductItemBean>> otherGrouponRequest = new FormResultRequest(UrlConstants.HOST + "Product/OtherGrouponList",
                this, this,
                new TypeToken<RequestResult<List<OtherProductItemBean>>>() {
                }.getType());
        otherGrouponRequest.setRequestParams(ajaxParams);
        showLoadingDialog("");
        executeRequest(otherGrouponRequest);
    }

    private void loadMoreData() {
        JSONWrapAjaxParams ajaxParams = getParams();
        ajaxParams.putCommonTypeParam("Page", getCurrPage());
        FormResultRequest<List<OtherProductItemBean>> otherGrouponRequest = new FormResultRequest(UrlConstants.HOST + "Product/OtherGrouponList",
                new Response.Listener<RequestResult<List<OtherProductItemBean>>>() {
                    @Override
                    public void onResponse(RequestResult<List<OtherProductItemBean>> requestResult) {
                        mLvContent.onRefreshComplete();
                        if (requestResult.flag == 1 && requestResult.getRs() != null) {
                            mAdapter.addItems(requestResult.getRs());
                            if (requestResult.getRs().size() >= 10) {
                                mLvContent.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                            } else {
                                mLvContent.setMode(PullToRefreshBase.Mode.DISABLED);
                            }
                        } else {
                            mLvContent.setMode(PullToRefreshBase.Mode.DISABLED);
                        }
                    }
                }, this,
                new TypeToken<RequestResult<List<OtherProductItemBean>>>() {
                }.getType());
        otherGrouponRequest.setRequestParams(ajaxParams);
        executeRequest(otherGrouponRequest);
    }

    @NonNull
    private JSONWrapAjaxParams getParams() {
        if (ajaxParams == null) {
            ajaxParams = new JSONWrapAjaxParams();
            ajaxParams.putCommonTypeParam("MerchantID", productDetailsBean.getMerchantID());
            ajaxParams.putCommonTypeParam("ProductId", productDetailsBean.getProductId());
            ajaxParams.putCommonTypeParam("PageSize", 10);
        }
        return ajaxParams;
    }

    public void setProductDetails(ProductDetailsBean.ProductBean productDetails) {
        this.productDetailsBean = productDetails;
    }

    @Override
    public void onResponse(RequestResult<List<OtherProductItemBean>> requestResult) {
        dismissLoadingDialog();
        isFirstLoadData = true;
        if (requestResult.flag == 1 && requestResult.getRs() != null) {
            mAdapter.setGroup(requestResult.getRs());
        }
        mLvContent.setMode(mAdapter.getCount() >= 10 ? PullToRefreshBase.Mode.PULL_FROM_END : PullToRefreshBase.Mode.DISABLED);
        otherCouponTitle.setVisibility(mAdapter.getCount() > 0 ? View.VISIBLE : View.GONE);
    }

    public int getCurrPage() {
        return (mAdapter.getCount() + (10 - 1)) / 10;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String pId = mAdapter.getItem(i - 2).getProductId();
        Intent intent = new Intent(getActivity(), ProductDetailsActivity1.class);
        intent.putExtra(ProductDetailsActivity1.PRODUCT_ID, pId);
        intent.putExtra(ProductDetailsActivity1.PRODUCT_IMG, mAdapter.getItem(i - 2).getProductPicUrl());
        showActivity(getActivity(), intent);
    }

    class ProductListAdapter extends BaseAda<OtherProductItemBean> {
        public ProductListAdapter(Context context) {
            super(context);
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            OtherProductItemHolder holder;
            if (view == null) {
                holder = new OtherProductItemHolder(getActivity());
                view = holder.getRootView();
            } else {
                holder = (OtherProductItemHolder) view.getTag();
            }
            holder.setData(getItem(i));
            return view;
        }
    }

    /* * ***********************
     * WebView
     * ***********************/
    private void createWebView() {
        graphicDetails = View.inflate(context, R.layout.product_graphic_details_layout, null);
        mWebView = (CustomWebView) graphicDetails.findViewById(R.id.wv_product_introduction);
        otherCouponTitle = graphicDetails.findViewById(R.id.ll_other_coupon_title);
        initWebView();
        if(productDetailsBean != null){
            mWebView.loadData(productDetailsBean.getProductIntroduction(),"text/html;charset='utf-8'", "utf-8");
        }
    }

    private void initWebView() {
        mWebView.getSettings().setDefaultTextEncodingName("utf-8");
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                mWebView.setVerticalScrollBarEnabled(false);
                mWebView.setVerticalScrollbarOverlay(false);
                mWebView.setHorizontalScrollBarEnabled(false);
                mWebView.setHorizontalScrollbarOverlay(false);
                mWebView.setBackgroundColor(Color.parseColor("#ffffff"));
                hideBuiltInZoomControls(mWebView);
                mWebView.setCanTouchZoom(false);
                // 不会闪黑屏
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                WebSettings settings = mWebView.getSettings();
                settings.setUseWideViewPort(true);
                settings.setLoadWithOverviewMode(true);
                settings.setSupportZoom(true);
                settings.setJavaScriptEnabled(true);
                settings.setTextSize(WebSettings.TextSize.NORMAL);
            }
        });
    }

    private void hideBuiltInZoomControls(WebView view) {
        if (Build.VERSION.SDK_INT < 11) {
            try {
                Field field = WebView.class.getDeclaredField("mZoomButtonsController");
                field.setAccessible(true);
                ZoomButtonsController zoomCtrl = new ZoomButtonsController(view);
                zoomCtrl.getZoomControls().setVisibility(View.GONE);
                field.set(view, zoomCtrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                WebSettings settings = view.getSettings();
                Method method = WebSettings.class.getMethod("setDisplayZoomControls", boolean.class);
                method.invoke(settings, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /* *************** WebView end ************************/

}
